//
//  menuViewController.m
//  i18n
//
//  Created by Patrick De Caluwe on 10/2/11.
//  Copyright 2011 patrick.decaluwe@student.uclouvain.be. All rights reserved.
//

#import "menuViewController.h"
#import "i18nViewController.h"
#import "newUserViewController.h"
#import "SignInViewController.h"
#import "loadXMLViewController.h"
#import "wordsUpAndDown.h"
#import "SelectVocaViewController.h"
#import "SyncManager.h"

@implementation menuViewController

i18nViewController *gViewController;
loadXMLViewController *gLoadXMLViewController;
newUserViewController *nuViewController;

-(IBAction)fastQuizClicked:(id)sender
{
    /*
    gViewController = [[[i18nViewController alloc] initWithNibName:@"i18nViewController" bundle:nil] autorelease];
    [self presentModalViewController:gViewController animated:YES];    
     */
    
    wordsUpAndDownViewController *vc = [[[wordsUpAndDownViewController alloc] initWithNibName:@"wordsUpAndDown" bundle:nil] autorelease];
    [self presentModalViewController:vc animated:YES];
    
}

-(IBAction)loadXMLClicked:(id)sender
{
    gLoadXMLViewController = [[[loadXMLViewController alloc] initWithNibName:@"loadXMLViewController" bundle:nil] autorelease];
    [self presentModalViewController:gLoadXMLViewController animated:YES];    
}

-(IBAction) newUserClicked:(id)sender
{
    nuViewController = [[[newUserViewController alloc] initWithNibName:@"newUserViewController" bundle:nil] autorelease];
    [self presentModalViewController:nuViewController animated:YES];
}

-(IBAction)selectVocaClicked:(id)sender
{
    SelectVocaViewController *svViewController = [[[SelectVocaViewController alloc] initWithNibName:@"SelectVocaViewController" bundle:nil] autorelease];
    
    [self presentModalViewController:svViewController animated:YES];
}

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)didReceiveMemoryWarning
{
    // Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
    
    // Release any cached data, images, etc that aren't in use.
}

#pragma mark - View lifecycle

- (void)viewDidLoad
{  
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
}

- (void)viewDidUnload
{
    [super viewDidUnload];
    // Release any retained subviews of the main view.
    // e.g. self.myOutlet = nil;
}

- (void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];
    
    SyncManager *syncMgr = [[SyncManager alloc] initWithUIView:self.navigationController.view];
    [syncMgr sync];
    
    if (![self didSignedIn]) {
        [self signIn];
    }
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    // Return YES for supported orientations
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}

-(void)signIn
{
    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"사용자 확인" message:@""
                                                   delegate:self
                                          cancelButtonTitle:@"취소"
                                          otherButtonTitles:@"신규 사용자", @"기존 사용자", nil];
    
    [alert show];
}

- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    switch (buttonIndex) {
        case 0:
            // cancel
            exit(0);
            break;
            
        case 1:
            // 새로운 사용자
            loader = [[DataLoader alloc] initWithTag:@"newuser"
                                                 url:@"http://i18n.ohmyenglish.co.kr/php/add_member.php"
                                            delegate:self
                                           superView:self.navigationController.view];

            break;

        case 2:
            // 기존 사용자
            nuViewController = [[[newUserViewController alloc] initWithNibName:@"newUserViewController" bundle:nil] autorelease];
            [self presentModalViewController:nuViewController animated:YES];

            break;
    }
}

- (BOOL)didSignedIn
{
    NSUserDefaults *prefs = [NSUserDefaults standardUserDefaults];
    BOOL signedIn = [prefs boolForKey:@"signedin"];
    NSString *userId = [[NSUserDefaults standardUserDefaults] objectForKey:@"userid"];
    
    return signedIn || ((userId != nil) && ([userId length] > 0));
}

-(void)makeSignedIn:(NSString*)userid
{
    NSUserDefaults *prefs = [NSUserDefaults standardUserDefaults];
    [prefs setBool:YES forKey:@"signedin"];
    [prefs setObject:userid forKey:@"userid"];
    [prefs synchronize];
}


#pragma mark - DataLoader

- (void)dataLoader:(DataLoader *)loader didFinishWithData:(NSMutableData *)data tag:(NSString *)tag {
    if (data == nil) {
        UIAlertView *av = [[UIAlertView alloc] initWithTitle:@"에러"
                                                     message:@"데이터를 가져오지 못했습니다."
                                                    delegate:nil
                                           cancelButtonTitle:@"확인"
                                           otherButtonTitles:nil];
        [av show];

        return;
    }
    
    xmlParseData = [[NSMutableArray alloc] init];
    
    NSXMLParser *parser = [[NSXMLParser alloc] initWithData:data];
    [parser setDelegate:self];
    [parser parse];
}

- (void)parser:(NSXMLParser *)parser
didStartElement:(NSString *)elementName
  namespaceURI:(NSString *)namespaceURI
 qualifiedName:(NSString *)qName
    attributes:(NSDictionary *)attributeDict {  

    if ([elementName isEqualToString:@"RESPONSE"]) {
        NSString *userId = [NSString stringWithFormat:@"%@", [attributeDict objectForKey:@"member_srl"]];
        NSLog(@"member_srl = %@", userId);
        
        [self makeSignedIn:userId];
        
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"회원정보"
                                   message:[NSString stringWithFormat:@"회원 ID는 %@입니다. 다른 기기에서 해당 ID를 사용하시면 학습 내용을 동기화하실 수 있습니다.", userId]
                                  delegate:nil
                         cancelButtonTitle:@"확인"
                         otherButtonTitles:nil];
        [alert show];
    }
}

- (void)cancelRequest {
    xmlParseData = nil;
    
    [loader cancel];
    loader = nil;
}

@end
